package com.heima.gateway.filter;

import com.heima.gateway.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Service;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Service
public class AuthFilter implements GlobalFilter, Ordered {
    /**
     * 过滤器执行的逻辑
     *
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 需求分析
        // 获取请求对象 和 响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        // 获取请求地址
        String path = request.getURI().getPath();
        // 判断请求地址是否需要鉴权,如果地址包含"/login",直接放行
        if (path.contains("/login")) {
            return chain.filter(exchange);
        }
        // 获取请求头
        // 需要判断请求头中是否有token
        String token = request.getHeaders().getFirst("token");
        // 判断token是否有效
        // 通过JWT工具解析token
        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);
            // 验证token
            int result = AppJwtUtil.verifyToken(claimsBody);
            // 判断token是否过期
            if (result == -1 || result == 0) {
                // token有效,需要提取token中的用户信息,添加到请求头中
                Integer userId = (Integer) claimsBody.get("userId");
                Object userName = claimsBody.get("userName");
                if (userId != 0) {
                    request.mutate().header("userId", userId.toString());
                    request.mutate().header("userName", userName.toString());
                }

                // 转发给后端的微服务
                return chain.filter(exchange);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        // 设置响应状态为401
        // 结束响应
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }

    /**
     * 过滤器执行的顺序,Gateway内部有大量的内置过滤器,每个过滤器都有自己的执行顺序,数值越小,优先级越高
     *
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
